var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var multer = require('multer');

var indexRouter = require('./routes/login');
var usersRouter = require('./routes/users');
var severPage = require('./routes/index')
var enroll =require('./routes/enroll.js')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


var upload = multer({ dest: './public/images/' })
app.use(function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');//自定义中间件，设置跨域需要的响应头。
  res.header('Access-Control-Allow-Headers', '*');
  next();
})
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', severPage);
app.use('/login', indexRouter);
app.use('/users', usersRouter);
app.use('/enroll', enroll);
app.post('/upload', upload.single('avatar'), require('./serve/upload.js'))
app.use('/dynamic',require('./routes/dynamic.js'))
app.use('/carousel', require('./routes/carousel.js'))
app.use('/activity',require('./routes/activity.js'))
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
